package com.hxkcloud.patient.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.beans.DrugBean;
import com.hxkcloud.patient.beans.StopDrugsRecordBean;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;

/**
 * 添加停药记录
 */
public class AddStopDrugActivity extends BaseActivity implements View.OnClickListener
{
    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_title_func;
    private TextView tv_adddrug_date;
    private TextView tv_drugName,tv_selectDrug;
    private Button bt_adddrug_save;
    private EditText edit_stopReason;
    private DrugBean bean;

    private String date;
    private CalendarPopWindow calendarPop;//选择服用日期
    private static int code = 100;

    private int intentType = 0; //0表示新增  1表示修改

    private StopDrugsRecordBean recordBean;
    private String recordId = "";

    //删除
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    public final static int requestCode = 1011;


    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_ADDSTOPTAKEDRUGS_SUCCESS:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datacommitsuccess);
                }
                setResult(Activity.RESULT_OK);
                finish();
                break;
            case MessageCode.NETWORKCODE_ADDSTOPTAKEDRUGS_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datacommitfail);
                }
                break;

            case MessageCode.NETWORKCODE_DELETESTOPDRUGS_SUCCESS:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletesuccess);
                }
                finish();
                break;
            case MessageCode.NETWORKCODE_DELETESTOPDRUGS_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletefail);
                }
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_stop_drug);
        initView();
        initPop();
        initPopup();
        initListener();
        initData();
    }

    public static void jumpToAddStopDrugActivity(Activity activity,DrugBean bean,int intentType,StopDrugsRecordBean recordBean)
    {
        Intent intent = new Intent(activity,AddStopDrugActivity.class);
        intent.putExtra("bean",bean);
        intent.putExtra("intentType",intentType);
        intent.putExtra("recordBean",recordBean);
        activity.startActivityForResult(intent,requestCode);
    }


    @Override
    protected void initView()
    {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_title_func = (TextView) findViewById(R.id.tv_title_func);
        tv_adddrug_date = (TextView) findViewById(R.id.tv_adddrug_date);
        tv_drugName = (TextView) findViewById(R.id.tv_drugName);
        tv_selectDrug = (TextView) findViewById(R.id.tv_selectDrug);
        bt_adddrug_save = (Button) findViewById(R.id.bt_adddrug_save);
        edit_stopReason = (EditText) findViewById(R.id.edit_stopReason);



        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.add_stopdrug_record));
        tv_title_func.setText(getResources().getText(R.string.delete));

        bt_adddrug_save.setBackgroundResource(R.drawable.bt_grey);
        bt_adddrug_save.setEnabled(false);
    }

    @Override
    protected void initListener()
    {
        iv_back.setOnClickListener(this);
        tv_adddrug_date.setOnClickListener(this);
        tv_selectDrug.setOnClickListener(this);
        bt_adddrug_save.setOnClickListener(this);
        tv_title_func.setOnClickListener(this);


        edit_stopReason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setClickEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData()
    {
        intentType = getIntent().getIntExtra("intentType",0);
        bean = (DrugBean) getIntent().getSerializableExtra("bean");
        recordBean = (StopDrugsRecordBean) getIntent().getSerializableExtra("recordBean");


        if(intentType == 0)
        {
            tv_drugName.setText(bean.getDrugName());
        }else
        {
            tv_title.setText("修改停药记录");
            tv_title_func.setVisibility(View.VISIBLE);

            tv_drugName.setText(recordBean.getMedicineName());
            tv_adddrug_date.setText(recordBean.getCreateTime());
            edit_stopReason.setText(recordBean.getContent());

            recordId = recordBean.getRecordId();

            bean = new DrugBean();
            bean.setDrugId(recordBean.getMedicineId());
            bean.setDrugName(recordBean.getMedicineName());

            date = recordBean.getCreateTime();

            setClickEnable();
        }

    }

    public void initPop()
    {
        calendarPop = new CalendarPopWindow(this);

        calendarPop.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                tv_adddrug_date.setText(calendar);//new SimpleDateFormat("yyyy-MM-dd")
                date = calendar;
                setClickEnable();
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.tv_adddrug_date:
                closeInputMethodManager();
                calendarPop.showBottom(ll_title);
                break;
            case R.id.tv_selectDrug: //更改药品
                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                    DrugListActivity.jumpToDrugListActivity(AddStopDrugActivity.this,loginInfo.getPatientId(),2,code);
                } else {
                    toastMsg("暂无药品可选，请先加入科室！");
                }
                break;
            case R.id.bt_adddrug_save:// bt_adddrug_save
                String content = edit_stopReason.getText().toString();
                if(containsEmoji(content))
                {
                    toastMsg("您输入的文本含有特殊字符");
                    return;
                }
                loading();
                YiJiaHuNetWorkUtils.addStopTakeDrugs(loginInfo.getUserId(),recordId,bean.getDrugId(), date, content, handler);
                break;
            case R.id.tv_title_func: //删除
                tv_easynotice_title.setText(R.string.deltherecord);
                tv_easynotice_cancel.setText(R.string.cancel);
                tv_easynotice_func.setText(R.string.delete);
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                YiJiaHuNetWorkUtils.deleteStopDrugs(recordId,handler);
                break;
        }
    }


    public void setClickEnable()
    {
        String content = edit_stopReason.getText().toString();
        if(date != null && !TextUtils.isEmpty(content))
        {
            bt_adddrug_save.setBackgroundResource(R.drawable.bt_green);
            bt_adddrug_save.setEnabled(true);
        }else
        {
            bt_adddrug_save.setBackgroundResource(R.drawable.bt_grey);
            bt_adddrug_save.setEnabled(false);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(code == requestCode && resultCode == Activity.RESULT_OK)
        {
            bean = (DrugBean) data.getSerializableExtra("bean");
            tv_drugName.setText(bean.getDrugName());
        }
    }


    /**
     * 删除弹框
     */
    private void initPopup() {
        //easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(AddStopDrugActivity.this);
            }
        });
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }
    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

}
